﻿using NPOI.HSSF.UserModel;
using SF.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SF.Ucenter.admin.finance
{
    public partial class businessapp_settlement : Web.UI.ManagePage
    {
        protected int totalCount;
        protected int page;
        protected int pageSize;

        protected string action = string.Empty;
        protected string keywords = string.Empty;

        protected int business_settlement_id = 0;
        protected Model.sf_business_settlement model = new Model.sf_business_settlement();
        protected void Page_Load(object sender, EventArgs e)
        {
            this.keywords = DTRequest.GetQueryString("keywords");
            this.action = DTRequest.GetQueryString("action");
            this.business_settlement_id = int.Parse(DTRequest.GetQueryString("id"));

            model = new BLL.sf_business_settlement().GetModel(this.business_settlement_id);
            this.lbsettlementnum.Text = model.sf_finance_settlement_num;
            this.lbbusinessnum.Text = model.busnieseNum;
            this.lbbusinessname.Text = model.businessName;
            this.lbtotal.Text = model.total_amount.ToString();

            if (this.action == "export")
            {
                ExportData();
            } 

            this.pageSize = GetPageSize(10); //每页数量
            if (!IsPostBack) 
            { 
                ChkAdminLevel("app_list", DTEnums.ActionEnum.View.ToString()); //检查权限
                RptBind(" sf_finance_settlement_num = '" + model.sf_finance_settlement_num + "' and busnieseNum = '" + model.busnieseNum + "' and id>0" + CombSqlTxt(this.keywords), "id desc");
            }
        }

        private void ExportData()
        {
            string strWhere = " sf_finance_settlement_num = '" + model.sf_finance_settlement_num + "' and busnieseNum = '" + model.busnieseNum + "' and id>0" + CombSqlTxt(this.keywords) + " order by id desc";
            BLL.sf_businessapp_settlement bll = new BLL.sf_businessapp_settlement();
            System.Data.DataSet dsAppList = bll.GetList(strWhere);
            System.Data.DataSet dsAll = new System.Data.DataSet();
            System.Data.DataTable dTable = new System.Data.DataTable();

            dTable.Columns.Add("结算单编号");
            dTable.Columns.Add("商户编号");
            dTable.Columns.Add("商户名称");
            dTable.Columns.Add("合计");
            dTable.Columns.Add("结算时间");
            System.Data.DataRow row = dTable.NewRow();
            row["结算单编号"] = model.sf_finance_settlement_num;
            row["商户编号"] = model.busnieseNum;
            row["商户名称"] = model.businessName;
            row["合计"] = model.total_amount;
            row["结算时间"] = model.create_time;
            dTable.Rows.Add(row);
            dTable.TableName = "商户结算信息";
            dsAll.Tables.Add(dTable);

            foreach (System.Data.DataRow r in dsAppList.Tables[0].Rows) 
            {
                string settleNum = r["sf_finance_settlement_num"].ToString();
                string appNum = r["appNum"].ToString();
                BLL.sf_ordersettlement bll_order = new BLL.sf_ordersettlement();
                System.Data.DataSet ds_order = bll_order.GetList(" sf_finance_settlement_num = '" + settleNum + "' and appNum = '" + appNum + "' ");

                System.Data.DataTable dt_order = ds_order.Tables[0].Copy();
                Hashtable hsColumns = new Hashtable();
                hsColumns.Add("sf_finance_settlement_num", "结算单编号");
                hsColumns.Add("busnieseNum", "商户编号");
                hsColumns.Add("appNum", "公共服务号");
                hsColumns.Add("order_num", "订单编号");
                hsColumns.Add("payMoney", "销售金额");
                hsColumns.Add("amount", "结算金额");
                hsColumns.Add("create_time", "生成时间");

                //1、移除不必要的字段
                for (int i = dt_order.Columns.Count - 1; i >= 0; i--)
                {
                    string column_name = dt_order.Columns[i].ColumnName;
                    if (hsColumns.Contains(column_name) == false)
                    {
                        dt_order.Columns.Remove(column_name);
                    }
                }
                //2、调整列名称
                foreach (System.Data.DataColumn col in dt_order.Columns)
                {
                    col.ColumnName = hsColumns[col.ColumnName].ToString();
                }


                dt_order.TableName = r["appid_name"].ToString();
                dsAll.Tables.Add(dt_order);
            }

            HSSFWorkbook workbook = NPOIExcelHelper.GridToExcelByNPOI(dsAll);
            DownLoad(workbook,"商户结算单");
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="hssfWorkbook">excel工作簿</param>
        /// <param name="fileName">文件名</param>
        private void DownLoad(HSSFWorkbook hssfWorkbook, string fileName)
        {
            using (MemoryStream memoryStram = new MemoryStream())
            {
                //把工作簿写入到内存流中
                hssfWorkbook.Write(memoryStram);
                //设置输出编码格式
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                //设置输出流
                Response.ContentType = "application/octet-stream";
                //防止中文乱码
                fileName = HttpUtility.UrlEncode(fileName);
                //设置输出文件名
                Response.AppendHeader("Content-Disposition", "filename=" + fileName + ".xls");
                //输出
                Response.BinaryWrite(memoryStram.GetBuffer());
            }
        } 

        /// <summary>
        /// 取得网站根目录的物理路径
        /// </summary>
        /// <returns></returns>
        public static string GetRootPath()
        {
            string AppPath = "";
            HttpContext HttpCurrent = HttpContext.Current;
            if (HttpCurrent != null)
            {
                AppPath = HttpCurrent.Server.MapPath("~");
            }
            else
            {
                AppPath = AppDomain.CurrentDomain.BaseDirectory;
                if (Regex.Match(AppPath, @"\\$", RegexOptions.Compiled).Success)
                    AppPath = AppPath.Substring(0, AppPath.Length - 1);
            }
            return AppPath;
        }

        #region 数据绑定=================================
        private void RptBind(string _strWhere, string _orderby)
        {
            this.page = DTRequest.GetQueryInt("page", 1);
            txtKeywords.Text = this.keywords;
            BLL.sf_businessapp_settlement bll = new BLL.sf_businessapp_settlement();
            this.rptList.DataSource = bll.GetList(this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
            this.rptList.DataBind();

            //绑定页码
            txtPageNum.Text = this.pageSize.ToString();
            string pageUrl = Utils.CombUrlTxt("businessapp_settlement.aspx",
                "id={0}&keywords={1}&page={2}",
                model.id.ToString() ,txtKeywords.Text, "__id__");

            PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 组合SQL查询语句==========================
        protected string CombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and (appNum like  '%" + _keywords + "%'  )");
            }

            return strTemp.ToString();
        }
        #endregion

        #region 返回每页数量=============================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Utils.GetCookie("finance_app_page_size", "DTcmsPage"), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        //关健字查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("businessapp_settlement.aspx",
                "id={0}&keywords={1}", 
                model.id.ToString(), txtKeywords.Text));
        }

        //设置分页数量
        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int _pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    Utils.WriteCookie("finance_app_page_size", "DTcmsPage", _pagesize.ToString(), 14400);
                }
            }
            Response.Redirect(Utils.CombUrlTxt("businessapp_settlement.aspx",
                "id={0}&keywords={2}",
                model.id.ToString(), txtKeywords.Text));
        }
    }
}